package com.yhj.reggie.controller;


import com.yhj.reggie.common.R;
import com.yhj.reggie.util.UUIDUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@RestController
@RequestMapping("/common")
public class CommonController {

    //读取配置文件上传路径
    @Value("${reggie.path}")
    private String baseDIr;

    @RequestMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        //1.获取上传文件的文件名
        String filename = file.getOriginalFilename();

        //2.获取文件扩展名
        String fileExtName = filename.substring(filename.lastIndexOf("."));

        //创建唯一随机的文件名
        String newFileName = UUIDUtils.getUUID() + fileExtName;

        //3.将文件保存到指定目录
        File dir = new File(baseDIr);
        if (!dir.exists()){
            dir.mkdir();
        }

        //进行保存
        file.transferTo(new File(baseDIr + newFileName));

        return R.success(newFileName);
    }

    @RequestMapping("/download")
    public void download(@RequestParam("name") String fileName, HttpServletResponse response) throws IOException {
        //输入流
        FileInputStream inputStream = new FileInputStream(baseDIr + fileName);
        //输出流
        ServletOutputStream outputStream = response.getOutputStream();

        IOUtils.copy(inputStream, outputStream);
    }

}
